package jmine.tec.utils.cripto.key.impl;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;

import org.apache.commons.logging.LogFactory;

import jmine.tec.utils.cripto.key.GeradorChaveRSA;
import jmine.tec.utils.cripto.key.PublicKeyLocator;
import jmine.tec.utils.io.IOUtils;
import jmine.tec.utils.io.ResourceFinder;

/**
 * Implementacao trivial de {@link PublicKeyLocator}
 * 
 * @author takeshi
 */
public class ClasspathPublicKeyLocator implements PublicKeyLocator {

    /**
     * {@inheritDoc}
     */
    public PublicKey getPublicKey(String keyName) {
        URL url = ResourceFinder.findClasspathResourceAbsolutePath(this.getClass(), keyName);
        if (url == null) {
            return null;
        }
        InputStream input = null;
        try {
            input = url.openStream();
            return GeradorChaveRSA.leChavePublica(input);
        } catch (InvalidKeySpecException e) {
            LogFactory.getLog(getClass()).warn("InvalidKeySpec on classpath resource: " + url, e);
            return null;
        } catch (IOException e) {
            LogFactory.getLog(getClass()).warn("IOException reading classpath resource: " + url, e);
            return null;
        } finally {
            if (input != null) {
                IOUtils.closeResourceLogException(input, getClass());
            }
        }
    }

}
